package com.jjkj.environmental.environmental.ui.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.widget.CheckBox
import android.widget.LinearLayout
import com.jjkj.environmental.environmental.R
import com.jjkj.environmental.environmental.utils.Setting

@SuppressLint("InflateParams")
class FuelChooseDialog(context: Context, onChoose: OnChoose) {
    private var alertDialog: AlertDialog
    private var fuelType: MutableList<String>

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.check_dialog_view, null)
        val layout = view.findViewById<LinearLayout>(R.id.ll_fuel_type)
        fuelType = ArrayList()
        Setting.FUEL_TYPE.entries.forEach {
            val checkBox = CheckBox(context)
            checkBox.text = it.value
            checkBox.setOnCheckedChangeListener { _, isChecked ->
                if (isChecked) {
                    fuelType.add(checkBox.text.toString())
                } else {
                    fuelType.remove(checkBox.text.toString())
                }
            }
            layout.addView(checkBox)
        }
        alertDialog = AlertDialog.Builder(context)
                .setTitle("燃油类型选择")
                .setView(view)
                .setNegativeButton("取消") { _, _ -> this.cancel() }
                .setPositiveButton("确认") { _, _ ->
                    val result = StringBuilder()
                    for (i in fuelType.indices) {
                        result.append(fuelType[i])
                        if (i < fuelType.size - 1) {
                            result.append(".")
                        }
                    }
                    onChoose.choose(result.toString())
                }
                .create()
    }

    fun show() {
        if (!alertDialog.isShowing) {
            alertDialog.show()
        }
    }

    private fun cancel() {
        if (alertDialog.isShowing) {
            alertDialog.cancel()
        }
    }

    interface OnChoose {
        fun choose(fuelType: String)
    }
}